
package com.zj.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zj
 * @version 1.0.0
 * @ClassName ThreadPoolTaskConfig
 * @Description 默认线程池
 * @createTime 2024年11月26日 20:50
 */
@EnableAsync
@Configuration
public class ThreadPoolTaskConfig {

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数，就算没有人物也会存在
        executor.setCorePoolSize(8);
        //核心线程会超时关闭
//        executor.setAllowCoreThreadTimeOut(true);
        //阻塞队列长度，当核心线程数达到最大时，会放入阻塞队列等待执行
        executor.setQueueCapacity(128);
        //当超过核心线程数且阻塞队列已满，会创建新的线程来执行任务
        //当阻塞队列已满且线程数==maxPoolSize,会执行拒绝策略
        executor.setMaxPoolSize(64);
        //当线程空闲时间达到keepAliveseconds时，maxpool的线程会销毁到corePoolSize
        executor.setKeepAliveSeconds(60);
        //拒绝策略 new ThreadPoolExecutor.AbortPolicy():抛出异常
        //new ThreadPoolExecutor.CallerRunsPolicy() 由调用方执行
        //new ThreadPoolExecutor.DiscardOldestPolicy() 抛弃最老的
        //new ThreadPoolExecutor.DiscardPolicy() 抛弃
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }
}
